

import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TextInput, TouchableOpacity, Modal, FlatList, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface CCRecipient {
  id: string;
  name: string;
  department?: string;
}

interface Contact {
  id: string;
  name: string;
  department: string;
}

const ApprovalPassScreen = () => {
  const router = useRouter();
  const params = useLocalSearchParams();
  
  const [approvalComment, setApprovalComment] = useState('');
  const [ccRecipients, setCCRecipients] = useState<CCRecipient[]>([]);
  const [isCCSelectorVisible, setIsCCSelectorVisible] = useState(false);
  const [ccSearchKeyword, setCCSearchKeyword] = useState('');
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [filteredContacts, setFilteredContacts] = useState<Contact[]>([]);

  const processInstanceId = params.processInstanceId as string || 'demo-id';

  useEffect(() => {
    // 如果有传入的审批意见，填充到文本框
    if (params.comment) {
      setApprovalComment(decodeURIComponent(params.comment as string));
    }
    
    // 加载联系人列表
    loadContactList();
  }, [params.comment]);

  useEffect(() => {
    // 过滤联系人
    if (ccSearchKeyword.trim() === '') {
      setFilteredContacts(contacts);
    } else {
      setFilteredContacts(
        contacts.filter(contact =>
          contact.name.toLowerCase().includes(ccSearchKeyword.toLowerCase()) ||
          contact.department.toLowerCase().includes(ccSearchKeyword.toLowerCase())
        )
      );
    }
  }, [ccSearchKeyword, contacts]);

  const loadContactList = () => {
    // 模拟联系人数据
    const mockContacts: Contact[] = [
      { id: '1', name: '张三', department: '技术部' },
      { id: '2', name: '李四', department: '人力资源部' },
      { id: '3', name: '王五', department: '财务部' },
      { id: '4', name: '赵六', department: '市场部' },
      { id: '5', name: '钱七', department: '行政部' }
    ];
    setContacts(mockContacts);
    setFilteredContacts(mockContacts);
  };

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    } else {
      router.push(`/p-approval_detail?processInstanceId=${processInstanceId}`);
    }
  };

  const handleCancelPress = () => {
    router.push(`/p-approval_detail?processInstanceId=${processInstanceId}`);
  };

  const handleConfirmApprovePress = () => {
    Alert.alert(
      '确认通过',
      '确定要通过此审批吗？',
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '确定',
          onPress: () => {
            console.log('执行审批通过操作', {
              processInstanceId,
              comment: approvalComment,
              ccRecipients
            });
            
            // 跳转到审批流程页面
            router.push(`/p-approval_process?processInstanceId=${processInstanceId}&action=approve&comment=${encodeURIComponent(approvalComment)}`);
          },
        },
      ]
    );
  };

  const handleAddCCPress = () => {
    setIsCCSelectorVisible(true);
    setCCSearchKeyword('');
  };

  const handleCloseCCSelector = () => {
    setIsCCSelectorVisible(false);
    setCCSearchKeyword('');
  };

  const handleContactSelect = (contact: Contact) => {
    // 检查是否已添加
    const isAlreadyAdded = ccRecipients.some(recipient => recipient.id === contact.id);
    if (isAlreadyAdded) {
      return;
    }

    setCCRecipients(prev => [...prev, { id: contact.id, name: contact.name, department: contact.department }]);
  };

  const handleRemoveCCRecipient = (id: string) => {
    setCCRecipients(prev => prev.filter(recipient => recipient.id !== id));
  };

  const renderCCRecipient = ({ item }: { item: CCRecipient }) => (
    <View style={styles.ccRecipientItem}>
      <Text style={styles.ccRecipientName}>{item.name}</Text>
      <TouchableOpacity
        style={styles.removeCCButton}
        onPress={() => handleRemoveCCRecipient(item.id)}
        activeOpacity={0.7}
      >
        <FontAwesome6 name="xmark" size={12} color="#9CA3AF" />
      </TouchableOpacity>
    </View>
  );

  const renderContactItem = ({ item }: { item: Contact }) => (
    <TouchableOpacity
      style={styles.contactItem}
      onPress={() => handleContactSelect(item)}
      activeOpacity={0.7}
    >
      <View style={styles.contactInfo}>
        <View style={styles.contactAvatar}>
          <Text style={styles.contactAvatarText}>{item.name.charAt(0)}</Text>
        </View>
        <View style={styles.contactDetails}>
          <Text style={styles.contactName}>{item.name}</Text>
          <Text style={styles.contactDepartment}>{item.department}</Text>
        </View>
      </View>
      <FontAwesome6 name="plus" size={16} color="#6366F1" />
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <TouchableOpacity
            style={styles.backButton}
            onPress={handleBackPress}
            activeOpacity={0.7}
          >
            <FontAwesome6 name="arrow-left" size={20} color="#D1D5DB" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>审批通过</Text>
        </View>
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        {/* 审批基本信息 */}
        <View style={styles.approvalInfoSection}>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.approvalInfoCard}
          >
            <View style={styles.approvalInfoHeader}>
              <View style={styles.approvalInfoLeft}>
                <Text style={styles.approvalTitle}>员工请假申请</Text>
                <View style={styles.approvalMeta}>
                  <View style={styles.approvalMetaItem}>
                    <FontAwesome6 name="user" size={12} color="#6366F1" />
                    <Text style={styles.approvalMetaText}>李小明</Text>
                  </View>
                  <View style={styles.approvalMetaItem}>
                    <FontAwesome6 name="clock" size={12} color="#6366F1" />
                    <Text style={styles.approvalMetaText}>2024-01-15 09:30</Text>
                  </View>
                </View>
              </View>
              <View style={styles.approvalStatus}>
                <Text style={styles.approvalStatusText}>审批中</Text>
              </View>
            </View>
            
            {/* 当前节点信息 */}
            <View style={styles.currentNodeContainer}>
              <View style={styles.currentNodeInfo}>
                <FontAwesome6 name="location-dot" size={14} color="#6366F1" />
                <Text style={styles.currentNodeLabel}>当前节点</Text>
              </View>
              <Text style={styles.currentNodeName}>部门经理审批</Text>
            </View>
          </LinearGradient>
        </View>

        {/* 审批意见 */}
        <View style={styles.commentSection}>
          <Text style={styles.sectionTitle}>审批意见</Text>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.commentCard}
          >
            <TextInput
              style={styles.commentInput}
              value={approvalComment}
              onChangeText={setApprovalComment}
              placeholder="请输入您的审批意见..."
              placeholderTextColor="#9CA3AF"
              multiline
              numberOfLines={4}
              textAlignVertical="top"
            />
          </LinearGradient>
        </View>

        {/* 抄送人 */}
        <View style={styles.ccSection}>
          <View style={styles.ccSectionHeader}>
            <Text style={styles.sectionTitle}>抄送人</Text>
            <TouchableOpacity
              style={styles.addCCButton}
              onPress={handleAddCCPress}
              activeOpacity={0.7}
            >
              <FontAwesome6 name="circle-plus" size={14} color="#6366F1" />
              <Text style={styles.addCCButtonText}>添加抄送人</Text>
            </TouchableOpacity>
          </View>
          <LinearGradient
            colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.ccCard}
          >
            {ccRecipients.length > 0 ? (
              <FlatList
                data={ccRecipients}
                renderItem={renderCCRecipient}
                keyExtractor={(item) => item.id}
                numColumns={3}
                scrollEnabled={false}
                columnWrapperStyle={styles.ccRecipientRow}
              />
            ) : (
              <Text style={styles.noCCMessage}>暂无抄送人，点击"添加抄送人"按钮添加</Text>
            )}
          </LinearGradient>
        </View>

        {/* 底部间距 */}
        <View style={styles.bottomSpacing} />
      </ScrollView>

      {/* 底部固定操作栏 */}
      <View style={styles.bottomActionBar}>
        <TouchableOpacity
          style={styles.cancelButton}
          onPress={handleCancelPress}
          activeOpacity={0.8}
        >
          <Text style={styles.cancelButtonText}>取消</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.confirmButton}
          onPress={handleConfirmApprovePress}
          activeOpacity={0.8}
        >
          <LinearGradient
            colors={['#6366F1', '#8B5CF6']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.confirmButtonGradient}
          >
            <FontAwesome6 name="check" size={16} color="#FFFFFF" />
            <Text style={styles.confirmButtonText}>确认通过</Text>
          </LinearGradient>
        </TouchableOpacity>
      </View>

      {/* 选择抄送人弹窗 */}
      <Modal
        visible={isCCSelectorVisible}
        transparent
        animationType="fade"
        onRequestClose={handleCloseCCSelector}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContainer}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>选择抄送人</Text>
              <TouchableOpacity
                style={styles.modalCloseButton}
                onPress={handleCloseCCSelector}
                activeOpacity={0.7}
              >
                <FontAwesome6 name="xmark" size={20} color="#9CA3AF" />
              </TouchableOpacity>
            </View>
            
            <View style={styles.modalContent}>
              <View style={styles.searchContainer}>
                <FontAwesome6 name="magnifying-glass" size={16} color="#9CA3AF" style={styles.searchIcon} />
                <TextInput
                  style={styles.searchInput}
                  value={ccSearchKeyword}
                  onChangeText={setCCSearchKeyword}
                  placeholder="搜索联系人"
                  placeholderTextColor="#9CA3AF"
                />
              </View>
              
              <FlatList
                data={filteredContacts}
                renderItem={renderContactItem}
                keyExtractor={(item) => item.id}
                style={styles.contactList}
                showsVerticalScrollIndicator={false}
              />
            </View>
            
            <View style={styles.modalFooter}>
              <TouchableOpacity
                style={styles.confirmCCButton}
                onPress={handleCloseCCSelector}
                activeOpacity={0.8}
              >
                <Text style={styles.confirmCCButtonText}>确定</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

export default ApprovalPassScreen;

